<?php

namespace app\admin\model;

use app\lib\Qiniu;

class Cookbookstep extends Base
{

    // 数据表名称
    //protected $table;

    // 当前模型名称 不带前缀
    protected $name = 'cookbook_step';

    // 数据表主键 复合主键使用数组定义 不设置则自动获取
    protected $pk = 'id';


    protected static function init()
    {
        // 新增后
        self::event('after_insert', function ($model) {
            if ($model->img_url) {
                Image::where('img_url', $model->img_url)->update(['related_id' => $model->id, 'controller' => 'Cookbookstep', 'related_table' => 'cookbook_step']);
            }
        });

        // 更新后 -- 快捷注册
        self::afterUpdate(function ($model) {
            if ($model->img_url) {
                Image::where('img_url', $model->img_url)->update(['related_id' => $model->id, 'controller' => 'Cookbookstep', 'related_table' => 'cookbook_step']);
            }
        });
    }

    public static function _after_delete($id){
        if(is_array($id)){
            $list = Image::where('related_table', 'cookbook_step')->whereIn('related_id', $id)->select();
        }else{
            $list = Image::where('related_table', 'cookbook_step')->where('related_id', $id)->select();
        }

        $Qiniu = new Qiniu();
        foreach ((array)$list as $item) {
            $key = substr(strrchr($item['img_url'], '/'), 1);
            // 删除七牛图片
            $res = $Qiniu->delImg($key);

            Image::where('id', $item['id'])->delete();
        }
    }
}